import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {ApiResponse, AuthData, LoginRequest, SignupRequest, User, UserData, UserInfo} from '../models/auth';
import {Observable, tap} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  constructor(
    private http: HttpClient
  ) { }
  public userInfo: User = {
    id: '',
    username: '',
    email: ''
  }
  login(loginData: LoginRequest): Observable<ApiResponse<AuthData>> {
    return this.http.post<ApiResponse<AuthData>>('/users/login', loginData).pipe(
      tap(res => {
        if (res.success && res.data?.token) {
          this.setToken(res.data?.token)
          // this.setUserInfo(res.data.user)
          this.userInfo = res.data.user
        }
      }),
    )
  }
  register(registerData: SignupRequest): Observable<ApiResponse<AuthData>> {
    return this.http.post<ApiResponse<AuthData>>('/users/register', registerData)
  }
  getUserInfo(): Observable<ApiResponse<UserData>> {
    return this.http.get<ApiResponse<UserData>>('/users/profile');
  }
  private setToken(token: string): void {
    localStorage.setItem('access_token', token);
    console.log(token);
  }
  private removeToken(): void {
    localStorage.removeItem('access_token');
  }
  getToken(): string | null {
    return localStorage.getItem('access_token')
  }
  // private setUserInfo(userInfo: User): void {
  //   localStorage.setItem('user_info', JSON.stringify(userInfo));
  // }

  logout(): void {
    this.removeToken();
  }

}
